// miniprogram/pages/player/player.js
let musicList = [],
  playingSongIndex = 0,
  currentSong = {},
  history = false;
const backgroundAudioManager = wx.getBackgroundAudioManager(); // 获取全局唯一背景音频播放器
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bgUrl: '', // bgurl
    songUrl: '', // 歌曲url
    isShowLyric: false, // 歌词/封面切换
    isPlaying: false, // 是否播放
    lyric: '', // 歌词
    isSame: false //是否为同一首歌
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    playingSongIndex = options.index;
    musicList = wx.getStorageSync('musicList');
    history = options.history;
    this._getPlaySongInfo(options.musicId);
    // if (options.storyPlayList) {
    //   this._storyPlaySongInfo();
    // } else {
    //   this._getPlaySongInfo()
    // }
  },
  _getPlaySongInfo(musicId) {
    if (musicId == app.getPlayMusicId()) {
      this.setData({
        isSame: true
      })
    } else {
      this.setData({
        isSame: false
      })
    }
    if (!this.data.isSame) {
      backgroundAudioManager.stop();
    }
    const musicInfo = musicList[playingSongIndex];
    if (history) {
      currentSong = {
        url: musicInfo.url,
        title: musicInfo.title,
        id: musicInfo.id,
        singer: musicInfo.singer,
        coverImgUrl: musicInfo.coverImgUrl,
      }
      this._getMusicInfo(currentSong);
      /**
       * 全局设置playingMusicId
       */
      app.setPlayMusicId(musicInfo.id);
      this.setData({
        lyric: musicInfo.lyrics
      })
    } else {
      if (musicInfo.file128) {
        currentSong = {
          url: musicInfo.file128,
          title: musicInfo.songname,
          id: musicInfo.id,
          singer: musicInfo.singer,
          coverImgUrl: musicInfo.res_cover,
        }
        this._getMusicInfo(currentSong);
        /**
         * 全局设置playingMusicId
         */
        app.setPlayMusicId(musicInfo.id);
        this.setData({
          lyric: musicInfo.lyrics
        })
      } else {
        /**
         * 全局设置playingMusicId
         */
        app.setPlayMusicId(musicInfo.id);
        wx.cloud.callFunction({
          name: 'music',
          data: {
            $url: "musicPlay",
            musicid: musicInfo.id
          }
        }).then(res => {
          if (res.result.data[0].url == null) {
            wx.showToast({
              title: '暂无播放权限！',
            })
            return false;
          }
          currentSong = {
            url: res.result.data[0].url,
            title: musicInfo.name,
            id: musicInfo.id,
            singer: musicInfo.ar[0].name,
            coverImgUrl: musicInfo.al.picUrl,
          }
          this._getMusicInfo(currentSong);
          //获取歌词
          wx.cloud.callFunction({
            name: 'music',
            data: {
              $url: 'lyric',
              musicid: musicInfo.id
            }
          }).then(res => {
            let lyric = '暂无歌词';
            const lrc = JSON.parse(res.result).lrc;
            if (lrc) {
              lyric = lrc.lyric
            }
            // console.log(lyric)
            this.setData({
              lyric: lyric
            })
          })
        })
      }
    }


  },
  _getMusicInfo(data) {
    if (!this.data.isSame) {
      backgroundAudioManager.src = data.url;
      backgroundAudioManager.title = data.title;
      backgroundAudioManager.singer = data.singer
      backgroundAudioManager.coverImgUrl = data.coverImgUrl;
      backgroundAudioManager.epname = data.title;
    }
    this.setData({
      bgUrl: data.coverImgUrl,
      isPlaying: true
    })
    wx.setNavigationBarTitle({
      title: data.title,
    })
    //保持播放历史
    this.savePlayHistory();
  },
  /**
   * 暂停/播放
   */
  togglePlay() {
    if (this.data.isPlaying) {
      backgroundAudioManager.pause();
    } else {
      backgroundAudioManager.play();
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  /**
   * 上一首
   */
  prev() {
    playingSongIndex--
    if (playingSongIndex < 0) {
      playingSongIndex = musicList.length - 1;
    }
    this._getPlaySongInfo()
  },
  /**
   * 下一首
   */
  next() {
    playingSongIndex++
    if (playingSongIndex > musicList.length - 1) {
      playingSongIndex = 0;
    }
    this._getPlaySongInfo()
  },
  /**
   * 歌词切换
   */
  togglePlayLyric() {
    this.setData({
      isShowLyric: !this.data.isShowLyric
    })
  },
  /**
   * 歌词联动
   */
  updataTime(opt) {
    this.selectComponent(".lyric").updataTime(opt.detail.currentTime)
  },
  /**
   * progress-bar 控制播放暂停
   * 
   */
  musicPlay() {
    this.setData({
      isPlaying: true
    })
  },
  musicPause() {
    this.setData({
      isPlaying: false
    })
  },
  savePlayHistory() {
    const openId = app.globalData.openId;
    let history = wx.getStorageSync(openId);
    let bHave = false;
    for (let i = 0, len = history.length; i < len; i++) {
      if (history[i].url == currentSong.url) {
        bHave = true
        break;
      }
    }
    if (!bHave) {
      history.unshift(currentSong);
    }
    wx.setStorage({
      key: openId,
      data: history,
    })
  },
  onShareAppMessage() {

  }
})